package com.module.filter;

import com.alibaba.fastjson.JSON;
import com.module.framework.domain.LoginUser;
import com.module.framework.domain.ResponseResult;
import com.module.framework.enums.AppHttpCodeEnum;
import com.module.framework.utils.JwtUtil;
import com.module.framework.utils.RedisCache;
import com.module.framework.utils.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @Author JiHuiQin
 * @Date 2022/2/14 22:12
 * @Version 1.0
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

	@Autowired
	private RedisCache redisCache;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		// 获取token
		String token = request.getHeader("token");
		String userId;
		// 不存在token，放行
		if (!StringUtils.hasText(token)) {
			filterChain.doFilter(request, response);
			return;
		}
		// 解析token
		try {
			Claims claims = JwtUtil.parseJWT(token);
			userId = claims.getSubject();
		} catch (Exception e) {
			e.printStackTrace();
			ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
			WebUtils.renderString(response, JSON.toJSONString(result));
			return;
		}
		// 根据userId从redis中获取用户信息
		String redisKey = "login:" + userId;
		LoginUser loginUser = redisCache.getCacheObject(redisKey);
		if (Objects.isNull(loginUser)) {
			throw new RuntimeException("用户未登录");
		}
		// 存入SecurityContextHolder，获取权限信息
		UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, null);
		SecurityContextHolder.getContext().setAuthentication(authenticationToken);
		// 放行
		filterChain.doFilter(request, response);
	}
}
